package com.scorpionstudio.girlstoryshop;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.scorpionstudio.girlstoryshop.adapter.LoadMoreGridView;
import com.scorpionstudio.girlstoryshop.adapter.TwoColumnAdapter;
import com.scorpionstudio.girlstoryshop.bean.DialogWarningNetwork;
import com.scorpionstudio.girlstoryshop.bean.ItemClothes;
import com.scorpionstudio.girlstoryshop.utils.JsonParser;
import com.scorpionstudio.girlstoryshop.utils.NetWork;
import com.scorpionstudio.girlstoryshop.utils.Variable;


public class DetailMenuTwoColumnActivity extends ScorpionActivity {
	private LoadMoreGridView mGridView;
	private String TAG = "DetailMenuTwoCoumn";
	private MyTask mTask = null;
	private ProgressDialog pDialog;
	private ItemClothes mClothes = new ItemClothes();
	private JSONArray mJsonArray = null;
	private int i = 1;
	private int positionList = 0;
	private String linkLoad = "";
	private String rootLINK = "";
	private String rootSize = Variable.KEY_SIZE;
	private int sizeOfPage = 0;
    private TwoColumnAdapter mAdapter;
    private ProgressBar mProgress;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_two_clumn_activity);
		initVariable();

        mProgress = (ProgressBar) findViewById(R.id.prg_load_more);
    }
	public void initVariable(){
        mAdapter = new TwoColumnAdapter(this);
		mGridView = (LoadMoreGridView) findViewById(R.id.grd_detail_twocolumn);
        mGridView.setAdapter(mAdapter);
        mGridView.setSelection(positionList);
		mGridView.setmOnLoadMoreListener(new LoadMoreGridView.OnLoadMoreListener() {
			
			@Override
			public void onLoadMore() {
//				Log.e(TAG, "size :" + getSize(Variable.LINK_MYPHAM + "1", Variable.KEY_SIZE));
				if(i < sizeOfPage){
					i++;
					positionList += 10;
					LoadData(linkLoad + i,rootLINK,rootSize);
				}
			}
		});
		Bundle bundleGetMenu = getIntent().getExtras();
		int indexMenu = bundleGetMenu.getInt(Variable.MENU_INDEX);
		switch (indexMenu) {
		case 0:
			LoadData(Variable.LINK_MYPHAM + "1",Variable.ROOT_MYPHAM,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_MYPHAM;
			rootLINK = Variable.ROOT_MYPHAM;
//			sizeOfPage = getSize(Variable.LINK_MYPHAM + "1", Variable.KEY_SIZE);
			break;
		case 1:
			LoadData(Variable.LINK_THAMMY + "1",Variable.ROOT_THAMMY,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_THAMMY;
			rootLINK = Variable.ROOT_THAMMY;
//			sizeOfPage = getSize(Variable.LINK_THAMMY + "1", Variable.KEY_SIZE);
			break;
		case 2:
			LoadData(Variable.LINK_MU + "1",Variable.ROOT_MU,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_MU;
			rootLINK = Variable.ROOT_MU;
//			sizeOfPage = getSize(Variable.LINK_MU + "1", Variable.KEY_SIZE);
			break;
		case 3:
			LoadData(Variable.LINK_QUANAO + "1",Variable.ROOT_QUANAO,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_QUANAO;
			rootLINK = Variable.ROOT_QUANAO;
//			sizeOfPage = getSize(Variable.LINK_QUANAO + "1", Variable.KEY_SIZE);
			break;
		case 4:
			LoadData(Variable.LINK_KHANTAT + "1",Variable.ROOT_KHANTAT,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_KHANTAT;
			rootLINK = Variable.ROOT_KHANTAT;
//			sizeOfPage = getSize(Variable.LINK_KHANTAT + "1", Variable.KEY_SIZE);
			break;
		case 5:
			LoadData(Variable.LINK_GIAYDEP + "1",Variable.ROOT_GIAYDEP,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_GIAYDEP;
			rootLINK = Variable.ROOT_GIAYDEP;
//			sizeOfPage = getSize(Variable.LINK_GIAYDEP + "1", Variable.KEY_SIZE);
			break;
		case 6:
			LoadData(Variable.LINK_PHUKIEN + "1",Variable.ROOT_PHUKIEN,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_PHUKIEN;
			rootLINK = Variable.ROOT_PHUKIEN;
//			sizeOfPage = getSize(Variable.LINK_PHUKIEN + "1", Variable.KEY_SIZE);
			break;
		case 7:
			LoadData(Variable.LINK_TUI + "1",Variable.ROOT_TUI,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_TUI;
			rootLINK = Variable.ROOT_TUI;
//			sizeOfPage = getSize(Variable.LINK_TUI + "1", Variable.KEY_SIZE);
			break;
		case 8:
			LoadData(Variable.LINK_VI + "1",Variable.ROOT_VI,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_VI;
			rootLINK = Variable.ROOT_VI;
//			sizeOfPage = getSize(Variable.LINK_VI + "1", Variable.KEY_SIZE);
			break;
		case 9:
			LoadData(Variable.LINK_AONGU + "1",Variable.ROOT_AONGU,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_AONGU;
			rootLINK = Variable.ROOT_AONGU;
//			sizeOfPage = getSize(Variable.LINK_AONGU + "1", Variable.KEY_SIZE);
			break;
		case 10:
			LoadData(Variable.LINK_GIADINH + "1",Variable.ROOT_GIADINH,Variable.KEY_SIZE);
			linkLoad = Variable.LINK_GIADINH;
			rootLINK = Variable.ROOT_GIADINH;
//			sizeOfPage = getSize(Variable.LINK_GIADINH + "1", Variable.KEY_SIZE);
			break;
		case 11:
			LoadData(Variable.LINK + "1", Variable.ROOT_HOMEPAGE,Variable.KEY_SIZE);
			linkLoad = Variable.LINK;
			rootLINK = Variable.ROOT_HOMEPAGE;
//			sizeOfPage = getSize(Variable.LINK + "1", Variable.KEY_SIZE);
			break;
		default:
			break;
		}
//		mGridView.setOnItemClickListener(this);
//		TwoColumnAdapter mAdapter = new TwoColumnAdapter(DetailMenuTwoColumnActivity.this, android.R.layout.simple_list_item_1, mArrayList);
//		mGridView.setAdapter(mAdapter);
	}
	/*@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent mDetail = new Intent(DetailMenuTwoColumnActivity.this,DetailClothesActivity.class);
		startActivityForResult(mDetail, 100);
	}*/
	@Override
	public void onBackPressed() {
		Intent mBackMain = new Intent(DetailMenuTwoColumnActivity.this,MainSaleActivity.class);
		startActivity(mBackMain);
		finish();
	}
	public void backMain(View v){
		Intent mBackMain = new Intent(DetailMenuTwoColumnActivity.this,MainSaleActivity.class);
		startActivity(mBackMain);
		finish();
	}
	private void LoadData(String link,String root,String rootSize) {
        try {
            if (NetWork.isOnline(getApplicationContext()) == true) {
                mTask = new MyTask();
                mTask.execute(link,root,rootSize);
            } else {
                DialogWarningNetwork dialogWarningNetwork = new DialogWarningNetwork(DetailMenuTwoColumnActivity.this) {
                    @Override
                    public void onYesClicked() {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
                        startActivityForResult(intent, NetWork.TURN_ON_NETWORK);
                        onBackPressed();
                    }
                };
                dialogWarningNetwork.show();
            }


        } catch (Exception ex) {
            Log.e("error load", ex.toString());
        }
    }
	private class MyTask extends AsyncTask<String, Void, ArrayList<ItemClothes>> {
        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(DetailMenuTwoColumnActivity.this);
            pDialog.setMessage("Tải dữ liệu...");
            pDialog.setCancelable(true);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    cancel(true);
                    mGridView.onLoadMoreComplete();
                }
            });
            if (mAdapter.getCount() <= 0){
                pDialog.show();
            }else{
                mProgress.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected ArrayList<ItemClothes> doInBackground(String... params) {
            ArrayList<ItemClothes> arrayResult = getData(params[0],params[1]);
            sizeOfPage = getSize(params[0],params[2]);
            Log.e(TAG,"size :" + sizeOfPage + "pa1 :" + params[0] + "pa2 :" + params[1]);
            if (null != arrayResult && arrayResult.size() > 0) {
                publishProgress();
            }
            return arrayResult;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            //mTextView.setText(itemsMusic.get(0).getName());
        }

        @Override
        protected void onPostExecute(ArrayList<ItemClothes> result) {
            Log.e("count item :", "" + result.size());
            if (null != pDialog && pDialog.isShowing()) {
                mTask.cancel(true);
                pDialog.cancel();
                pDialog.dismiss();
            }
            if (mProgress.isShown()){
                mProgress.setVisibility(View.GONE);
            }
            if (result != null && result.size() > 0) {
                mAdapter.addAll(result);
        		mGridView.onLoadMoreComplete();
                mAdapter.notifyDataSetChanged();
            } else {
                AlertDialog.Builder mAlert = new AlertDialog.Builder(
                        DetailMenuTwoColumnActivity.this);
                mAlert.setTitle("Không có dữ liệu");
                mAlert.setMessage(
                        "Xảy ra lỗi trong quá trình tải. Bạn có muốn tải lại không ?")
                        .setPositiveButton("Có",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        try {
                                            mTask = new MyTask();
                                            mTask.execute(Variable.LINK);
                                        } catch (Exception ex) {
                                            Log.e("error load", ex.toString());
                                        }
                                    }
                                })
                        .setNegativeButton("Không",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.cancel();
                                        dialog.dismiss();
                                        pDialog.cancel();
                                        pDialog.dismiss();
                                        mTask.cancel(true);
                                        finish();
                                    }
                                });
                AlertDialog mAlertDialog = mAlert.create();
                mAlertDialog.show();
            }
        }
    }
	/*
	 * Get size of gridview.
	 */
	public int getSize(String link,String root){
		int size = 0;
			String json = JsonParser.getJSONString(link);
	        JSONObject object;
			try {
				object = (JSONObject) new JSONTokener(json).nextValue();
		        JSONArray mJsonArray  = object.getJSONArray(root);
		        JSONObject objJson  = mJsonArray.getJSONObject(0);
		        size = objJson.getInt(Variable.KEY_ROOT_SIZE);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		return size;
	}
    public ArrayList<ItemClothes> getData(String url,String root) {
        ArrayList<ItemClothes> list = new ArrayList<ItemClothes>();
        try {
            String json = JsonParser.getJSONString(url);
            JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
            mJsonArray  = object.getJSONArray(root);
            for (int i = 0; i < mJsonArray.length(); i++) {
                JSONObject objJson = mJsonArray.getJSONObject(i);
                mClothes.setID(objJson.getInt(Variable.ID));
                mClothes.setUrlImg(objJson.getString(Variable.IMAGE));
                mClothes.setDescriptionImg(objJson.getString(Variable.NAME));
                mClothes.setCostItems(objJson.getString(Variable.COST));
                mClothes.setDetail(objJson.getString(Variable.DETAILS));
                list.add(mClothes);
                mClothes = new ItemClothes();
            }
        } catch (Exception e) {
            Log.e("load data","json " + e.toString());
        }
        return list;
    }
   
}
